﻿



import Request from '../../base/request.js?t=202511041006'
import Storage from '../../base/storage.js?t=202511041006'
import { imageBaseUrl, getRecentYears, getMonthList, getBrowserInfo, downloadfun } from "../../base/utils.js?t=202511041006"
const Composition = (proxy) => {
    const data = reactive({
        cIndex: 1,
        proxy: "",
        messageTest: '',
        timer: null,
        mockData: {
            title: "",
            data: [

            ],
        },
        tabList: [{
            label: '年度考核结果', value: 1
        }],
        tableTitle: '',
        statusList: [{
            label: '考评中', value: 2,

        }, {
            label: '待批准', value: 3,

        }, {
            label: '已批准', value: 4
        }],

        queryParams: {
            month: null,
            year: null,
        },
        main: "",

        pagination: {
            total: 0,
            current: 1,
            loading: true,
            pageSize: 50,
            showTotal: total => `总共 ${total} 项`,
            defaultPageSize: 10,
            // pageSizeOptions: ['5', '10', '15', '20'], // 可不设置使用默认
            showSizeChanger: true, // 是否显示pagesize选择
            showQuickJumper: false, // 是否显示跳转窗
        },

        EvaluationForm: {
            form: [],
            status: null
        },
        formList: [

        ],
        DepartmentTypeList: [],

        monthList: [

        ],
        columns1: [
            {
                title: '排行',
                dataIndex: 'a',
                key: 'a',
                align: 'center',
                width: 80,
                customRender: ({ index }) => {
                    return (params.pagination.value.current - 1) * params.pagination.value.pageSize + index + 1
                },
            },
            {
                title: '考核标题',
                dataIndex: 'PlanNoticeName',
                key: 'PlanNoticeName',
                align: 'center'

            },
            {
                title: '部门',
                dataIndex: 'DepartmentName',
                key: 'DepartmentName',
                align: 'center'
            },
            {
                title: '实际总分',
                dataIndex: 'TotalScore',
                key: 'TotalScore',
                align: 'center',
                sorter: (a, b) => a.TotalScore - b.TotalScore,
            },
            {
                title: '操作',
                dataIndex: 'd',
                key: 'd',
                align: 'center',
                title: '操作',
                key: 'action',
                align: 'center',
                customRender: function ({ record }) {




                    let detailBtn = h(antd.Button, {
                        type: "link",
                        onClick: () => methods.handleDetail(record, 0)
                    }, { default: () => '详情' })


                    return h(antd.Space, {
                    },
                        { default: () => [detailBtn] }
                    );



                }
            },

        ],
        columns: [
            {
                title: '排行',
                dataIndex: 'index',
                key: 'index',
                align: 'center',
                width: 80,
                customRender: ({ index }) => {
                    let arr = ['../Bussiness/img/svg/r1.png', '../Bussiness/img/svg/r2.png', '../Bussiness/img/svg/r3.png', '../Bussiness/img/svg/r4.png']



                    let r = h('img', {
                        src: arr[index],
                        style: "position:absolute;top:0;left:0;"
                    }, { default: () => '' })

                    let fdiv = h('div', {
                        style: index + 1 < 5 ? "width:40px;height:40px; position:relative;z-index:999;color:#fff;display:flex;justify-content:center;align-items:center;" : "width:40px;height:40px; position:relative;z-index:999;color:#000;display:flex;justify-content:center;align-items:center;"
                    }, { default: () => index + 1 < 10 ? '0' + (index + 1) : index + 1 })

                    let sdiv = h('div', {
                        style: "position:relative;width:40px;height:40px;"
                    }, { default: () => [r, fdiv] })
                    return sdiv
                },
            },
            {
                title: '年度',
                dataIndex: 'Years',
                key: 'aYears',
                align: 'center'

            },
            {
                title: '部门',
                dataIndex: 'DepartmentName',
                key: 'DepartmentName',
                align: 'center'
            },
            {
                title: '部门类型',
                dataIndex: 'DepartmentTypeName',
                key: 'DepartmentTypeName',
                align: 'center'
            },
            {
                title: '考评分(百分制)',
                dataIndex: 'TotalScore',
                key: 'TotalScore',
                align: 'center',
                sorter: (a, b) => {
                    return a.TotalScore - b.TotalScore
                },
                customRender: ({ text }) => {
                    return text || '-'
                },
            },

            {
                title: '状态',
                dataIndex: 'StatusName',
                key: 'StatusName',
                align: 'center',
                customRender: ({ text }) => {
                    return h(antd.Tag, {
                        color: "#108ee9",
                    }, { default: () => text });
                },
            },

            {
                title: '操作',
                dataIndex: 'd',
                key: 'd',
                align: 'center',
                title: '操作',
                key: 'action',
                align: 'center',
                customRender: function ({ record }) {


                    let approvalBtn = h(antd.Button, {
                        type: "link",
                        onClick: () => {
                            methods.handleModify(record, 1)
                        }
                    }, { default: () => '修改' })

                    let detailBtn = h(antd.Button, {
                        type: "link",
                        onClick: () =>
                            methods.handleDetail(record, 0)

                    }, { default: () => '详情' })








                    return h(antd.Space, {
                    },
                        { default: () => [record.IsEvalution ? approvalBtn : null, detailBtn] }
                    );


                }
            },

        ],
        dataSource: [],
        ocolumns: [
            {
                title: '序号',
                dataIndex: 'index',
                key: 'index',
                align: 'center',
                width: 80,
                customRender: ({ index }) => {
                    return (params.pagination.value.current - 1) * params.pagination.value.pageSize + index + 1
                },
            },
            {
                title: '通知标题',
                dataIndex: 'PlanNoticeName',
                key: 'PlanNoticeName',
                align: 'center'

            },
            {
                title: '部门',
                dataIndex: 'DepartmentName',
                key: 'DepartmentName',
                align: 'center'
            },
            {
                title: '部门类型',
                dataIndex: 'DepartmentTypeName',
                key: 'DepartmentTypeName',
                align: 'center'
            },
            {
                title: '考评总分',
                dataIndex: 'TotalScore',
                key: 'TotalScore',
                align: 'center',
                sorter: (a, b) => {
                    return a.TotalScore - b.TotalScore
                },
                customRender: ({ text }) => {
                    return text || '-'
                },
            },
            {
                title: '状态',
                dataIndex: 'StatusName',
                key: 'StatusName',
                align: 'center',
                customRender: ({ text }) => {
                    return h(antd.Tag, {
                        color: text == '批准' ? "#87d068" : "#108ee9",
                    }, { default: () => text });
                },



            },
            {
                title: '操作',
                dataIndex: 'd',
                key: 'd',
                align: 'center',
                title: '操作',
                key: 'action',
                align: 'center',
                customRender: function ({ text, record, index, column }) {

                    return h("div", {
                    },
                        [h(antd.Button, {
                            style: 'margin-right:4px',
                            type: "link",
                            onClick: () => methods.handleDetail(record, 0)
                        }, { default: () => '详情' })]
                    );



                }
            },

        ],
        odataSource: [],


        yearsList: [],
        columns3: [
            {
                title: '排行',
                dataIndex: 'a',
                key: 'a',
                align: 'center',
                width: 80,
                customRender: ({ index }) => {
                    return (params.pagination.value.current - 1) * params.pagination.value.pageSize + index + 1
                },
            },
            {
                title: '年度',
                dataIndex: 'a',
                key: 'a',
                align: 'center'

            },
            {
                title: '部门',
                dataIndex: 'b',
                key: 'b',
                align: 'center'
            },
            {
                title: '实际总分',
                dataIndex: 'c',
                key: 'c',
                align: 'center',
                sorter: (a, b) => a.c - b.c,
            },


        ],

        dataSource1: [],

        dataSource3: [],

        echartData: [],
        isLeader: false

    })
    let params = toRefs(data)
    let methods = {

        filter: (inputValue, path) => {
            return path.some(option => {
                return option.label.toString().toLowerCase().indexOf(inputValue.toString().toLowerCase()) > -1
            });


        },

        handleModify: (record) => {
            window.open(`/Performance/PerformanceMeansEvaluate?id=${record.Id}&planid=${record.PlanId}&o=1`, "_blank")

        },

        handleDetail: (record, status) => {
            window.open(`/Performance/PerformanceResultCheckDetail?id=${record.Id}&status=${record.Status}&isEdit=${status}`, "_blank")

        },
        GetYearsOption: () => {
            return new Promise((reslove, rej) => {
                Request({
                    url: "/performance/GetYearsOption",
                    method: 'post',
                }).then(res => {

                    params.formList.value = res.Data
                    params.EvaluationForm.value.form[0] = res.Data[0].value
                    params.EvaluationForm.value.form[1] = res.Data[0].children[0].value

                    reslove(1)

                })

            })

        },

        GetDepartmentTypeList: () => {
            Request({
                url: "/performance/GetDepartmentTypeList",
                method: 'post',

            }).then(res => {

                params.DepartmentTypeList.value = res.Data.map(e => {
                    return {
                        label: e.TypeName,
                        value: e.Id
                    }
                })


            })
        },
        Cchange: (e) => {


            methods.getTableList(true)
            methods.GetPerformanceChart()

        },
        GetPerformanceChart: () => {

            Request({
                url: "/performance/GetPerformanceChart",
                method: 'post',
                params: {
                    "PlanId": params.EvaluationForm.value.form && params.EvaluationForm.value.form[1],
                    Status: params.EvaluationForm.value.status,
                    DepartmentTypeId: params.EvaluationForm.value.DepartmentTypeId
                }
            }).then(res => {

                params.echartData.value = res.Data

                methods.initChart(params.echartData.value)


            })

        },

        initChart(data) {
            var myChart = echarts.init(params.proxy.value.$refs.main);

            // 指定图表的配置项和数据
            const option = () => {
                return {
                    backgroundColor: 'transparent',
                    tooltip: {
                        trigger: 'axis',
                        axisPointer: { // 坐标轴指示器，坐标轴触发有效
                            type: 'shadow' // 默认为直线，可选为：'line' | 'shadow'
                        },
                        formatter: function (params) {

                            return `${params[0].name}:${params[0].value}分`
                        }
                    },
                    grid: {
                        left: '2%',
                        right: '4%',
                        bottom: '14%',
                        top: '16%',
                        containLabel: true
                    },
                    legend: {
                        data: params.echartData.value.map(e => e.DepartmentName),
                        right: 10,
                        top: 12,
                        textStyle: {
                            color: "#000"
                        },
                        itemWidth: 12,
                        itemHeight: 10,
                        // itemGap: 35
                    },
                    xAxis: {
                        type: 'category',
                        data: params.echartData.value.map(e => e.DepartmentName),
                        axisLine: {

                            lineStyle: {
                                color: '#000',
                                type: 'dashed', // 线的类型
                            }
                        },
                        axisLabel: {
                            interval: 0,
                            rotate: 45,

                            textStyle: {
                                fontFamily: 'Microsoft YaHei'
                            }
                        },
                    },

                    yAxis: {
                        type: 'value',
                        name: "分数",
                        min: 0,

                        interval: 20,
                        axisLine: {
                            show: false,
                            lineStyle: {
                                color: '#000',
                            }
                        },
                        splitLine: {
                            show: true,
                            lineStyle: {
                                color: '#d8d8d8',
                                type: 'dashed', // 线的类型
                            }
                        },
                        axisLabel: {}
                    },
                    "dataZoom": [{
                        "show": true,
                        "height": 10,
                        "xAxisIndex": [
                            0
                        ],
                        bottom: '8%',
                        "start": 10,
                        "end": 90,
                        handleIcon: 'path://M306.1,413c0,2.2-1.8,4-4,4h-59.8c-2.2,0-4-1.8-4-4V200.8c0-2.2,1.8-4,4-4h59.8c2.2,0,4,1.8,4,4V413z',
                        handleSize: '110%',
                        handleStyle: {
                            color: "#d3dee5",

                        },
                        textStyle: {
                            color: "#000"
                        },
                        borderColor: "#90979c"
                    }, {
                        "type": "inside",
                        "show": true,
                        "height": 15,
                        "start": 1,
                        "end": 35
                    }],
                    series: [{
                        name: '1',
                        type: 'bar',
                        barWidth: '6%',
                        label: {
                            show: true, //开启显示
                            position: 'top', //在上方显示
                            formatter: '{c}分',//显示百分号
                            textStyle: { //数值样式
                                color: '#45c27d',//字体颜色
                                fontSize: 10//字体大小
                            }
                        },

                        itemStyle: {
                            normal: {
                                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
                                    offset: 0,
                                    color: '#18d36c'
                                }, {
                                    offset: 1,
                                    color: '#d1f6e2'
                                }]),
                                barBorderRadius: 8,
                            },
                        },
                        data: params.echartData.value.map(e => e.Score),
                    }]
                }
            }


            // 使用刚指定的配置项和数据显示图表。








            myChart.setOption(option(params.echartData.value));

            //document.querySelector('#ttmain').addEventListener('mouseover', () => {
            //    setTimeout(() => {
            //        console.log('鼠标移入暂停')
            //        clearInterval(params.timer.value)
            //        params.timer.value = null
            //        var app = {
            //            currentIndex: -1,
            //        };
            //    })
            //},true)
            //document.querySelector('#ttmain').addEventListener('mouseleave', () => {

            //    //if (params.timer.value) {
            //    //    console.log('已存在定时器')
            //    //    return
            //    //}
            //    var app = {
            //        currentIndex: -1,
            //    };
            //    console.log('鼠标移出回复')
            //    params.timer.value = setInterval(function () {

            //        var dataLen = option(params.echartData.value).series[0].data.length;

            //        // 取消之前高亮的图形
            //        myChart.dispatchAction({
            //            type: 'downplay',
            //            seriesIndex: 0,
            //            dataIndex: app.currentIndex
            //        });

            //        app.currentIndex = (app.currentIndex + 1) % dataLen;

            //        // 高亮当前图形
            //        myChart.dispatchAction({
            //            type: 'highlight',
            //            seriesIndex: 0,
            //            dataIndex: app.currentIndex,
            //        });

            //        // 显示 tooltip
            //        myChart.dispatchAction({
            //            type: 'showTip',
            //            seriesIndex: 0,
            //            dataIndex: app.currentIndex
            //        });


            //    }, 2000);
            //}, false)

            //params.timer.value=  setInterval(function () {

            //    var dataLen = option(params.echartData.value).series[0].data.length;

            //    // 取消之前高亮的图形
            //    myChart.dispatchAction({
            //        type: 'downplay',
            //        seriesIndex: 0,
            //        dataIndex: app.currentIndex
            //    });

            //    app.currentIndex = (app.currentIndex + 1) % dataLen;

            //    // 高亮当前图形
            //    myChart.dispatchAction({
            //        type: 'highlight',
            //        seriesIndex: 0,
            //        dataIndex: app.currentIndex,
            //    });

            //    // 显示 tooltip
            //    myChart.dispatchAction({
            //        type: 'showTip',
            //        seriesIndex: 0,
            //        dataIndex: app.currentIndex
            //    });


            //}, 2000);
        },
        generateTable(tableData, tableContainerId) {
            const smap = {
                rank: "排名",
                dept: "部门",
                deptType: "部门类型",
                mark: "考评分(百分制)",
            };
            // 获取目标容器元素
            var container = document.getElementById(tableContainerId);

            if (!container) return console.error("Container not found.");

            // 创建表格元素
            var table = document.createElement("table");
            table.className = "table center-table t table-striped table-bordered"; // 添加Bootstrap样式类



            // 创建表头
            var thead = document.createElement("thead");
            var headerRow = document.createElement("tr");

            // 假设所有对象都有相同的结构，取第一个对象的键作为表头
            var keys = Object.keys(tableData.data[0]);
            keys.forEach(function (key) {
                var th = document.createElement("th");
                th.textContent = smap[key];
                headerRow.appendChild(th);
            });

            thead.appendChild(headerRow);
            table.appendChild(thead);

            // 创建表体
            var tbody = document.createElement("tbody");
            tableData.data.forEach(function (item) {
                var row = document.createElement("tr");

                keys.forEach(function (key) {
                    var cell = document.createElement("td");
                    cell.textContent = item[key];
                    row.appendChild(cell);
                });

                tbody.appendChild(row);
            });

            table.appendChild(tbody);
            // 如果提供了表格标题，则创建 <caption> 元素并添加到表格

            // 清空并添加新表格到容器中
            container.innerHTML = ""; // 确保容器内没有其他内容
            if (tableData.title) {
                var caption = document.createElement("caption");
                caption.textContent = tableData.title;

                container.appendChild(caption);
            }
            container.appendChild(table);

        },
        onexport: () => {
            params.pagination.value.loading = true
            if (!params.EvaluationForm.value.form || params.EvaluationForm.value.form.length == 0) {
                return
            }
            let item = null
            for (let key in params.formList.value) {
                if (params.formList.value[key].value == params.EvaluationForm.value.form[0]) {
                    item = params.formList.value[key].children.filter(es => es.value == params.EvaluationForm.value.form[1])
                }
            }

            if (item) {
                params.tableTitle.value = `${item[0].label}`
            }

            params.mockData.value.title = `${params.tableTitle.value}排名表`

            params.mockData.value.data = params.dataSource.value.map((e, i) => {
                return {
                    'rank': i + 1,
                    'dept': e.DepartmentName,
                    'deptType': e.DepartmentTypeName,
                    'mark': e.TotalScore,
                }


            })
            methods.generateTable(params.mockData.value, "myTableContainer"); // '用户信息表' 是表格的标题

            html2canvas(document.querySelector("#myTableContainer")).then(async (canvas) => {


                const blob = await new Promise((resolve, reject) => {
                    canvas.toBlob(resolve, 'image/png');
                });

                // 创建 FormData 对象
                const formData = new FormData();
                formData.append('file', blob, 'pdf.png');

                Request({
                    url: "/download/uploadfile?Path=toPdf",
                    method: 'post',
                    data: formData
                }).then(res => {
                    Request({
                        url: `/Performance/ExportPdf?FileId=${res.Data[0].FileId}`,
                        method: 'post',

                    }).then(res => {
                        downloadfun('考核排名表', res.Data)
                        params.pagination.value.loading = false

                    })
                })
            });
        },
        init: () => {
            getBrowserInfo().catch(err => { console.log(err) })
            if (proxy) {
                params.proxy.value = proxy
            }
            const { message } = antd
            params.messageTest.value = message
            params.messageTest.value.config({
                top: `10vh`,
                duration: 7,
                maxCount: 1,
                rtl: true,
            });



            let info = Storage.get('AccountInfo', true)
            Request({
                url: "/Account/createJwtToken",
                method: 'post',
                data: {
                    "userName": info && info.UserNo
                }
            }).then(res => {
                Storage.set('token', res.Data,true)

                methods.GetYearsOption().then(res => {
                    methods.getTableList(true)
                    methods.GetPerformanceChart()
                    methods.GetDepartmentTypeList()
                })

                document.addEventListener('visibilitychange', function () {
                    if (document.visibilityState === 'visible') {

                        methods.GetYearsOption().then(res => {
                            methods.getTableList(true)
                            methods.GetPerformanceChart()
                            methods.GetDepartmentTypeList()
                        })

                    }
                });
            })
            params.yearsList.value = getRecentYears()
            params.monthList.value = getMonthList()
            params.dataSource1.value = []
        },

        GetEvalutionRole: () => {
            return new Promise((resolve, rej) => {

                Request({
                    url: "/performance/GetEvalutionRole",
                    method: 'post',

                }).then(res => {
                    params.isLeader.value = res.Data
                    resolve(params.isLeader.value)
                })


            })

        },

        getTableList: (isRresh) => {
            params.pagination.value.loading = true
            if (isRresh) {
                params.pagination.value.current = 1
            }
            methods.GetEvalutionRole().then(res => {

                if (params.cIndex.value == 1) {
                    if (res == true) {
                        Request({
                            url: "/performance/GetEvalutionPageList",
                            method: 'post',
                            params: {
                                page: params.pagination.value.current,
                                pageSize: params.pagination.value.pageSize
                            },
                            data: {
                                PlanId: params.EvaluationForm.value.form && params.EvaluationForm.value.form[1],
                                Status: params.EvaluationForm.value.status,
                                DepartmentTypeId: params.EvaluationForm.value.DepartmentTypeId
                            }
                        }).then(res => {

                            params.dataSource.value = res.Data
                            params.pagination.value.total = res.Data.length
                            params.pagination.value.loading = false
                        })
                        methods.GetPerformanceChart()
                    } else {
                        Request({
                            url: "/performance/GetDepartmentEvalutionPageList",
                            method: 'post',
                            params: {
                                page: params.pagination.value.current,
                                pageSize: params.pagination.value.pageSize,
                            },
                            data: {
                                Years: params.queryParams.value.year
                            }
                        }).then(res => {
                            params.odataSource.value = res.Data
                            params.pagination.value.total = res.Data.length
                            params.pagination.value.loading = false
                        })
                    }
                }
            })
        },

    }

    if (proxy) {

        params.proxy.value = proxy
    }
    const template = {
        test: {
            template: `<div @click="add">+</div> <div>{{testnum}}</div>`,

            setup() {

                return {
                    ...params,
                    ...methods,
                };
            }

        }
    }
    return {
        ...params,
        ...methods,
        template
    }
}
export default Composition